package locales

import (
	"embed"
	"github.com/nicksnyder/go-i18n/v2/i18n"
	"golang.org/x/text/language"
	"gopkg.in/yaml.v3"
	"log"
)

//go:embed *.yaml
var localeFS embed.FS

var (
	localizeEN *i18n.Localizer
	localizeZH *i18n.Localizer
)

func Init() {
	initEN()
	initZH()
}

func initEN() {
	bundleEN := i18n.NewBundle(language.English)
	bundleEN.RegisterUnmarshalFunc("yaml", yaml.Unmarshal)
	_, err := bundleEN.LoadMessageFileFS(localeFS, "en.yaml")
	if err != nil {
		log.Panicf("Error loading translation file for English: %v", err)
	}
	localizeEN = i18n.NewLocalizer(bundleEN, language.English.String())
}

func initZH() {
	bundleZH := i18n.NewBundle(language.Chinese)
	bundleZH.RegisterUnmarshalFunc("yaml", yaml.Unmarshal)
	_, err := bundleZH.LoadMessageFileFS(localeFS, "zh.yaml")
	if err != nil {
		log.Panicf("Error loading translation file for Chinese: %v", err)
	}
	localizeZH = i18n.NewLocalizer(bundleZH, language.Chinese.String())
}

func Translate(lang, key string, templateData map[string]interface{}) string {
	var localize *i18n.Localizer
	switch lang {
	case "zh-CN":
		localize = localizeZH
	default:
		localize = localizeEN
	}
	if localize == nil {
		log.Printf("WARN: No localizer for lang=%s, key=%s", lang, key)
		return ""
	}
	translation, err := localize.Localize(&i18n.LocalizeConfig{
		MessageID:    key,
		TemplateData: templateData,
	})
	if err != nil {
		log.Println("Translation error:", err, map[string]string{
			"lang": lang, "key": key,
		})
		return key
	}
	return translation
}

// T 获取国际化信息的函数
func T(language, messageID string) string {
	return Translate(language, messageID, nil)
}

// TD  获取国际化信息的函数
func TD(language, messageID string, data map[string]any) string {
	return Translate(language, messageID, data)
}
